<?php
  session_start();
  $uname = $_SESSION['uname'];
  $upass = $_SESSION['upass'];
  $newusername = $_POST['newusername'];
  $newuserpassword = $_POST['newuserpassword'];
  
  $fp = fopen('user.cfg', 'r');
	if($fp)
	{    
	    $arr = array();
		$auth = 0;
	    while(!feof($fp))
		{
			$name = stream_get_line( $fp, 1024, "\r\n" );
			$pass = stream_get_line( $fp, 1024, "\r\n" );
			$arr[$name] = $pass;
			if($uname==$name && $uname == "admin" && $upass==$pass)
			{
				$auth = 1;
			}
		}
		fclose($fp);

		if($auth == 1)
		{
				if(isset($arr[$newusername]))
				{
           $_SESSION['message'] = "User already exists, please choose a different name.";
           header('Location: AddUser.php');							
				}
				else
				{
					$fp = fopen('user.cfg', 'a');
					if($fp)
					{
						$arr[$newusername] = $newuserpassword;
						fwrite($fp, $newusername."\r\n".$arr[$newusername]."\r\n");
           $_SESSION['message'] = "Created user ".$newusername."<br/>";
           header('Location: AddUser.php');													
					}
					else
					{
             $_SESSION['message'] = "Cannot access the server.";
             header('Location: AddUser.php');
					}
				}

		}
		else
		{
       $_SESSION['message'] = "Authentication failed.";
       header('Location: AddUser.php');		
		}
	}
	else
	{
     $_SESSION['message'] = "Cannot access the server.";
     header('Location: AddUser.php');
	}
?>